package com.jxw.scanpen.activity;


import android.Manifest;

import android.content.Context;

import android.content.pm.PackageManager;
import android.database.ContentObserver;

import android.os.Build;

import android.os.Handler;
import android.os.HandlerThread;
import android.provider.Settings;

import android.text.TextUtils;

import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;

import android.view.View;

import com.jxw.scan_demo.R;
import com.jxw.scanpen.FunctionImpl;

import com.jxw.scanpen.comm.HYCamera;


import com.jxw.scan_demo.databinding.ActivityMainBinding;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 主界面
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> implements   HYCamera.OnCameraDataCallback, View.OnClickListener,
        FunctionImpl.ServiceCallback, FunctionImpl.ServiceListener {

    private boolean isOpenLight = false;

    /**
     * 裁剪状态判断，用于判断是否在进行裁剪
     * false：非裁剪进行的状态
     * true：裁剪正在进行的状态
     */
    private boolean caijianNewStatus = false;
    /**
     * 用于判断按压状态
     * true为未按压
     * false为已按压
     */
    private boolean touchKeyStatus = true;

    private HYCamera mCamera;

    private String multiRowResultAll;

    private String ocrTemp;

    boolean isInit;

    ExecutorService exeService = Executors.newFixedThreadPool(1);

    @Override
    protected void init() {

        mCamera = new HYCamera();
        mCamera.setCallback(this);
        mCamera.startCamera(this);
        initFuntion();


        //动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }
        }

        binding = getBinding();
        binding.setActivity(this);

    }

    @Override
    public void onPreviewFrame(byte[] data, int width, int height, int format) {
        if (isOpenLight) {
            exeService.execute(new Runnable() {
                @Override
                public void run() {
                    FunctionImpl.getInstance().pushOcr(data, 0);
                }
            });
        }
    }

    @Override
    public void onChangeSize(int width, int height) {
        if (isInit) {
            FunctionImpl.getInstance().initOcrSdk(0, 0, 0, 0, width, height, true, true);
        }
    }

    @Override
    public void onResult(String ocr_result, boolean temp) {
        ocrTemp = multiRowResultAll + ocr_result;
        Log.e("zzj", ocrTemp + "");
        if (!temp) {
            multiRowResultAll = ocrTemp;
        }
        if (!TextUtils.isEmpty(ocrTemp))
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    matchSetence(temp);
                    binding.tvScan.setText(ocrTemp);
                }
            });
    }

    @Override
    public void onSpeakTTSStart() {
    }

    @Override
    public void onSpeakTTSEnd() {
    }

    @Override
    public void onSpeakTTSError() {
    }

    @Override
    public void onTranslateResult(String trans) {

    }

    //扫描图片回调
    @Override
    public void onJpgResult(String path) {
        Log.e("zzj",  path + ":onJpgResult");
    }

    @Override
    public void onConnected() {
        isInit = true;
        FunctionImpl.getInstance().initOcrSdk(0, 0, 0, 0, HYCamera.mViewWidth, HYCamera.mViewHeight, true, true);
        FunctionImpl.getInstance().initAEEEngine();
    }

    @Override
    public void onDisconnected() {
        isInit = false;
        FunctionImpl.getInstance().start(MainActivity.this, this, MainActivity.this);
    }

    @Override
    public void onDied() {
        isInit = false;
    }

    //绑定ocr服务
    private void initFuntion() {
        FunctionImpl.getInstance().start(this, this, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
         FunctionImpl.getInstance().initOcrSdk(0, 0, 0, 0, HYCamera.mViewWidth, HYCamera.mViewHeight, true, true);
        //展示 显示的 页面
        setDataLayout();
        multiRowResultAll = "";
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void setDataLayout() {
        binding.tvScan.setText("");
        binding.rlMain.setVisibility(View.VISIBLE);
        binding.rlScan.setVisibility(View.GONE);
    }



    @Override
    public int setLayoutID() {
        return R.layout.activity_main;
    }

    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rl_back3:
            case R.id.iv_back3:
                finish();
                break;

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 286:
            case 5:
            case 27:
            case 131:
                onTouchKeyDown();
                return true;
            case 141:
                onTouchKeyUp();

                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void openLight() {
        mCamera.openLight();
    }

    private void onTouchKeyDown() {

        if (binding.rlNoData.getVisibility() == View.VISIBLE) {
            binding.rlNoData.setVisibility(View.GONE);
        }

        if (!isOpenLight && touchKeyStatus) {
            touchKeyStatus = false;
            binding.rlMain.setVisibility(View.GONE);
            binding.rlScan.setVisibility(View.VISIBLE);

            isOpenLight = true;
            openLight();
            setScanningEnable(true);
            exeService.execute(startRun);
        }
    }

    Runnable startRun = () -> FunctionImpl.getInstance().SPOCREngineStart();

    Runnable stopRun = () -> FunctionImpl.getInstance().SPOCREngineStop();

    private void setScanningEnable(boolean enable) {
        if (enable) {
            mCamera.startPreview(this);
        } else {
            mCamera.stopPreview(this);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 286:
            case 5:
            case 131:
                onTouchKeyUp();

                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void onTouchKeyUp() {
        if (isOpenLight) {
            isOpenLight = false;

                mCamera.closeLight();
                setScanningEnable(false);
                exeService.execute(stopRun);

        }
        if (!touchKeyStatus) {
            touchKeyStatus = true;
        }
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FunctionImpl.getInstance().stop();
        if (mCamera != null) {
            mCamera.stopCamera(this);
            mCamera = null;
        }
    }
}